#include "videothread.h"
#include <QDebug>

VideoThread::VideoThread(QObject *parent)
    : QThread{parent}
{

}

VideoThread::~VideoThread()
{
    if(decoder != NULL)
    {
        delete decoder;
    }
}

bool VideoThread::openVideoDecoder(AVCodecParameters *codec_params, int width, int height)
{
    if (codec_params == NULL)
    {
        return false;
    }
    //打开解码器
    if (decoder == NULL)
    {
        decoder = new Decoder();
    }
    int ret = true;
    if (!decoder->openDecoder(codec_params))
    {
        qDebug() << "video Decoder open failed!";
        ret = false;
    }
    qDebug() << "video Decoder open success!";
    return ret;
}

void VideoThread::addList(AVPacket *pkt)
{
    if (!pkt)return;
    //阻塞
    while (!exit_flag)
    {
        mux.lock();
        if (packs.size() < ((size_t)maxList))
        {
            packs.push_back(pkt);
            mux.unlock();
            break;
        }
        mux.unlock();
    }
}

void VideoThread::run()
{
    while (!exit_flag)
    {
        //没有数据
        if (packs.empty() || decoder == NULL )
        {
            continue;
        }

        AVPacket *pkt = packs.front();
        packs.pop_front();
        //发送给解码器pkg解码
        bool ret = decoder->sendAVPacketToDecoder(pkt);
        if (!ret)
        {
            continue;
        }
        //一次send 多次recv
        while (true)
        {
            //从解码器中获取解码后的数据
            AVFrame * frame = decoder->getDecodedFrame();
            if (!frame)
            {
                break;
            }
            qDebug() << frame->pts;
            av_frame_free(&frame);
        }
    }
}
